package com.ruoyi.project.system.service.impl;

import com.ruoyi.project.system.domain.ReservationAll;
import com.ruoyi.project.system.mapper.ReservationAllMapper;
import com.ruoyi.project.system.service.ReservationAllService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 预约服务实现类（类名修改 + 事务保证取消预约和回退名额原子性）
 */
@Service
public class ReservationAllServiceImpl implements ReservationAllService {

    @Autowired
    private ReservationAllMapper reservationAllMapper;

    @Override
    public List<ReservationAll> getMyReservations(Long userId) {
        return reservationAllMapper.selectReservationsByUserId(userId);
    }

    /**
     * 取消预约 + 回退名额（@Transactional 保证事务：要么都成功，要么都失败）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelReservationWithRestoreQuota(String resId) {
        // 步骤1：查询该预约关联的医生ID和预约日期（用于回退名额）
        ReservationAll reservation = reservationAllMapper.selectReservationForDaily(resId);
        if (reservation == null || reservation.getDoctorId() == null || reservation.getAppointmentDate() == null) {
            throw new RuntimeException("预约记录不存在或关联信息不完整");
        }

        // 步骤2：更新预约状态为已取消（resolve=3）
        int updateReservationRows = reservationAllMapper.updateResolveToCancel(resId);
        if (updateReservationRows <= 0) {
            throw new RuntimeException("更新预约状态失败");
        }

        // 步骤3：回退名额（temp_week_daily.remaining +1）
        int updateDailyRows = reservationAllMapper.updateDailyRemainingAddOne(
            reservation.getDoctorId(), 
            reservation.getAppointmentDate()
        );
        if (updateDailyRows <= 0) {
            throw new RuntimeException("回退名额失败（可能出勤表无对应记录）");
        }

        // 步骤4：所有操作成功，返回true
        return true;
    }
}